package com.bihu.bihudemo.auth.filter;

import com.bihu.bihudemo.controller.CapcharController;
import com.bihu.bihudemo.result.Result;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@Component("CaptcherFilter")
public class CaptcherFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;

        if(req.getMethod().equals("POST")&&req.getServletPath().equals("login")){
            String ver_code = req.getParameter("code");
            String real_code = (String)req.getSession().getAttribute(CapcharController.KAPSessionkey);
            if(!ver_code.equals(real_code)||ver_code.equals("")){
                res.setContentType("Content-Type:application/json;charset:utf-8");
                PrintWriter writer = res.getWriter();
                Result result = Result.error("验证码错误");
                writer.write(result.toString());
                writer.flush();
                writer.close();
                return;
            }else {
                filterChain.doFilter(req,res);
            }
        }else {
            filterChain.doFilter(req,res);
        }

    }
}
